package com.start.oss.storage;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.start.common.tools.UUIdTools;
import com.start.oss.StartOssData;
import com.start.oss.StartOssMinioStorageConfig;
import com.start.oss.entity.StartSysOssEntity;
import com.start.oss.utils.MinIoUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

@Component
public class MinioOssService implements StartOssStorageService {
    public static final String OSS_TYPE = "minio";
    @Autowired
    private MinIoUtils minIoUtils;
    @Autowired
    private StartOssMinioStorageConfig minioStorageConfig;

    @Override
    public String getOssTypeKey() {
        return OSS_TYPE;
    }

    @Override
    public String getOssLabel() {
        return "minio对象存储器";
    }

    @Override
    public StartSysOssEntity save(StartOssData data) {
        final MultipartFile file = data.getFile();
        String fileName = file.getOriginalFilename();
        if (data.isAutoRename()) {
            final int lastIndexOf = fileName.lastIndexOf(".");
            final String suffixName = fileName.substring(lastIndexOf);
            fileName = UUIdTools.createSnowFakeId() + suffixName;
        }
        String newFileName = LocalDateTimeUtil.format(LocalDateTime.now(), "YYYYMMdd") + "/" + fileName;
        final Boolean upload = minIoUtils.upload(file, newFileName, minioStorageConfig.getBucketName());
        if (!upload) {
            return null;
        }
        String url = minioStorageConfig.getMinioOssRootUrl() + "/" + minioStorageConfig.getBucketName() + "/" + newFileName;
        StartSysOssEntity entity = new StartSysOssEntity();
        entity.setOssUrl(url);
        entity.setOssName(newFileName);
        entity.setOssSrcName(file.getOriginalFilename());
        entity.setOssLocalPath(url);
        entity.setOssType(entity.getOssName().substring(entity.getOssName().lastIndexOf(".")));
        entity.setOssStorageType(getOssTypeKey());
        entity.setCreateTime(LocalDateTime.now());
        return entity;
    }

    @Override
    public byte[] getByOssEntity(StartSysOssEntity entity) {
        if (StringUtils.isEmpty(entity.getOssUrl())) {
            return null;
        }
        return minIoUtils.download(minioStorageConfig.getBucketName(), entity.getOssName());
    }

    @Override
    public boolean remove(StartSysOssEntity sysOssEntity) {
        return minIoUtils.removeObjects(minioStorageConfig.getBucketName(), sysOssEntity.getOssName());
    }

    @Override
    public byte[] getOssBySysOssEntity(StartSysOssEntity ossEntity) {
        final String ossName = ossEntity.getOssName();
        if (StringUtils.isEmpty(ossName)) return null;
        return minIoUtils.download(minioStorageConfig.getBucketName(), ossName);
    }
}
